import { ISelectGroupState } from '@/entrypoints/home/components/SelectGroup'
import { IListItem, ImportMode } from '@/utils/interfaces'
import { useCacheStore } from '@/utils/store/cacheStore'
import { AutoComplete, Button, Form, Select } from '@arco-design/web-react'
import React from 'react'
import {
    fetchSwaggerJson,
    swaggerJsonToApiItems,
} from '../../../utils/importer/swaggerJsonToApiItems'

export interface IImFromSwaggerJsonUrlProps {
    // 预览数据
    onPreview?: (
        items: IListItem[],
        recommendGroupOptions?: Partial<ISelectGroupState>,
    ) => void
}

const ImFromSwaggerJsonUrl: React.FC<IImFromSwaggerJsonUrlProps> = ({
    onPreview,
}) => {
    // 缓存
    const [importHistory, setImportHistory] = useCacheStore('importHistory', [])
    // 获取到的swagger.json数据
    const [swaggerJson, setSwaggerJson] = useState<any>({})
    // url
    const [url, setUrl] = useState<string>('')
    // filterByTag
    const [filterByTag, setFilterByTag] = useState<string>('')

    // 表单变化
    const handleUrlChange = async () => {
        if (!url) return
        const data = await fetchSwaggerJson(url)
        if (!data) return
        setSwaggerJson(data)
        setFilterByTag('')
        if (
            !importHistory?.find(
                (item) =>
                    item.url === url && item.mode === ImportMode.swaggerJsonUrl,
            )
        ) {
            setImportHistory([
                ...(importHistory || []),
                { url, mode: ImportMode.swaggerJsonUrl },
            ])
        }
    }

    // 点击导入预览
    const handleImportPreview = async () => {
        if (!url || !swaggerJson) return
        const apiItems = await swaggerJsonToApiItems(swaggerJson, {
            filterByTag,
            importData: {
                mode: ImportMode.swaggerJsonUrl,
                url,
            },
        })
        onPreview?.(apiItems || [], {
            newGroupName: filterByTag,
            addGroup: true,
        })
    }

    return (
        <div>
            {/* url */}
            <Form.Item label='url' rules={[{ required: true }]}>
                <AutoComplete
                    value={url}
                    onChange={(value) => setUrl(value)}
                    onBlur={() => handleUrlChange()}
                    data={importHistory
                        ?.filter(
                            (item) => item.mode === ImportMode.swaggerJsonUrl,
                        )
                        ?.map((item) => item.url)}
                    placeholder='请输入swagger.json的url'
                />
            </Form.Item>
            {/* 根据tag过滤 */}
            <Form.Item label='Tag'>
                <Select
                    value={filterByTag}
                    onChange={(value) => setFilterByTag(value)}
                    showSearch
                    filterOption={(input, option) => {
                        const label =
                            (option.props as any)?.children?.toString() || ''
                        return label.toLowerCase().includes(input.toLowerCase())
                    }}
                    options={swaggerJson?.tags?.map((t: any) => {
                        return { label: t?.name, value: t.name }
                    })}
                    placeholder='请选择Tag'
                />
            </Form.Item>

            {/* 预览 */}
            <div className='flex justify-end mb-4'>
                <Button onClick={handleImportPreview}>导入预览</Button>
            </div>
        </div>
    )
}

export default ImFromSwaggerJsonUrl
